import type { ResponseToolkit, ServerRoute, ReqRefDefaults } from "@hapi/hapi";
import { Notes, User } from "../../model/index";

let route: ServerRoute<ReqRefDefaults> = {
  path: "/copyNote",
  method: "post",
  handler: async (r: any, h: ResponseToolkit) => {
    try {
      const data = {
        ...r.payload,
        pid: r.userId,
      };
      delete data._id;
      delete data.cateObj;
      data.status = false;
      let user: any = await User.findOne({ _id: r.userId });
      let note: any = await new Notes({ ...data });
      await user.note.push(note._id);
      await note.save();
      await user.save();
      return { code: 200, data: true, message: "复制成功" };
    } catch (err: any) {
      if (err.code === 11000) {
        console.log(err);
        // 如果出现重复键值错误，则返回适当的错误消息
        return h.response().code(400);
      } else {
        // 否则返回通用错误消息
        console.log("error here");
        return h
          .response({
            error: { message: "服务器内部错误", code: err.code || 500 },
          })
          .code(500);
      }
    }
  },
  options: {
    plugins: {
      "hapi-swagger": {
        security: [{ apiKey: [] }],
      },
    },
    payload: {
      parse: true, // 解析请求体
      allow: "application/json", // 允许JSON格式的请求体
    },
    // auth: false,
    tags: ["api"],
  },
};
export default route;
